package com.treetao.union.web.controller.system;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.treetao.union.db.model.SysMenu;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.model.vo.ZtreeVO;
import com.treetao.union.web.constant.Constants;
import com.treetao.union.web.controller.BaseAdminController;

import lombok.extern.slf4j.Slf4j;

/**
 * 系统菜单管理
 */
@Slf4j
@Controller
@RequestMapping(Constants.AMIND_PREFIX + "/system/menu")
public class SysMenuController extends BaseAdminController{

    @GetMapping ("list")
    public String list(Model model){
        return "admin/system/menu/test";
    }

    @RequiresPermissions("sys:menu:list")
    @PostMapping("tree")
    @ResponseBody
    public RestResponse tree(){
        List<ZtreeVO> ztreeVOs = sysMenuService.showTreeMenus();
        log.info(JSONObject.toJSONString(ztreeVOs));
        return RestResponse.success().setData(ztreeVOs);
    }

    @RequiresPermissions("sys:menu:list")
    @PostMapping("treelist")
    @ResponseBody
    public RestResponse treelist(){
        Map<String,Object> map = Maps.newHashMap();
        map.put("parentId",null);
        map.put("isShow",false);
        return RestResponse.success().setData(sysMenuService.selectAllMenus(map));
    }

    @GetMapping("add")
    public String add(@RequestParam(value = "parentId",required = false) Long parentId,Model model){
        if(parentId != null){
        	SysMenu menu = sysMenuService.getById(parentId);
            model.addAttribute("parentMenu",menu);
        }
        return "admin/system/menu/add";
    }

    @RequiresPermissions("sys:menu:add")
    @PostMapping("add")
    @ResponseBody
    public RestResponse add(SysMenu menu){
        if(StringUtils.isBlank(menu.getName())){
            return RestResponse.failure("菜单名称不能为空");
        }
        if(StringUtils.isNotBlank(menu.getPermission())){
            if(sysMenuService.getCountByPermission(menu.getPermission())>0){
                return RestResponse.failure("权限标识已经存在");
            }
        }
        if(menu.getParentId() == null){
            menu.setLevel(1);
            QueryWrapper<SysMenu> q = new QueryWrapper<>();
            q.select("max(sort) s");
            q.isNull("parent_id");
            Object o = sysMenuService.getMap(q).get("s");
          //  Object o = sysMenuService.selectObj(Condition.create().setSqlSelect("max(sort)").isNull("parent_id"));
            int sort = 0;
            if(o != null){
                sort =  (Integer)o +10;
            }
            menu.setSort(sort);
        }else{
        	SysMenu parentMenu = sysMenuService.getById(menu.getParentId());
            if(parentMenu==null){
                return RestResponse.failure("父菜单不存在");
            }
            menu.setParentIds(parentMenu.getParentIds());
            menu.setLevel(parentMenu.getLevel()+1);
            
            QueryWrapper<SysMenu> q = new QueryWrapper<>();
            q.select("max(sort) s");
            q.eq("parent_id",menu.getParentId());
            Map<String, Object> map = sysMenuService.getMap(q);
            int sort = 0;
            if(map==null) {
            	sort = 1;
            } else {
            	 Object o = sysMenuService.getMap(q).get("s");
            	 if(o != null){
                     sort =  (Integer)o +10;
                 }
            }
           
//            Object o = sysMenuService.selectObj(Condition.create()
//                            .setSqlSelect("max(sort)")
//                            .eq("parent_id",menu.getParentId()));
            menu.setSort(sort);
        }
        sysMenuService.saveOrUpdateMenu(menu);
        menu.setParentIds(StringUtils.isBlank(menu.getParentIds())?menu.getId()+",":menu.getParentIds()+menu.getId()+",");
        sysMenuService.saveOrUpdateMenu(menu);
        return RestResponse.success();
    }

    @GetMapping("edit")
    public String edit(Long id,Model model){
    	SysMenu menu = sysMenuService.getById(id);
        model.addAttribute("menu",menu);
       return "admin/system/menu/edit";
    }

    @RequiresPermissions("sys:menu:edit")
    @PostMapping("edit")
    @ResponseBody
    public RestResponse edit(SysMenu menu){
        if(menu.getId() == null){
            return RestResponse.failure("菜单ID不能为空");
        }
        if (StringUtils.isBlank(menu.getName())) {
            return RestResponse.failure("菜单名称不能为空");
        }
        SysMenu oldMenu = sysMenuService.getById(menu.getId());
        if(!oldMenu.getName().equals(menu.getName())) {
            if(sysMenuService.getCountByName(menu.getName())>0){
                return RestResponse.failure("菜单名称已存在");
            }
        }
        if (StringUtils.isNotBlank(menu.getPermission())) {
            if(!oldMenu.getPermission().equals(menu.getPermission())) {
                if (sysMenuService.getCountByPermission(menu.getPermission()) > 0) {
                    return RestResponse.failure("权限标识已经存在");
                }
            }
        }
        if(menu.getSort() == null){
            return RestResponse.failure("排序值不能为空");
        }
        sysMenuService.saveOrUpdateMenu(menu);
        return RestResponse.success();
    }

    @RequiresPermissions("sys:menu:delete")
    @PostMapping("delete")
    @ResponseBody
    public RestResponse delete(@RequestParam(value = "id",required = false)Long id){
        if(id == null){
            return RestResponse.failure("菜单ID不能为空");
        }
        SysMenu menu = sysMenuService.getById(id);
        menu.setDelFlag(true);
        sysMenuService.saveOrUpdateMenu(menu);
        return RestResponse.success();
    }

    @PostMapping("isShow")
    @ResponseBody
    public RestResponse isShow(@RequestParam(value = "id",required = false)Long id,
                               @RequestParam(value = "isShow",required = false)String isShow){
        if(id == null){
            return RestResponse.failure("菜单ID不能为空");
        }
        if(isShow == null){
            return RestResponse.failure("设置参数不能为空");
        }else{
            if(!"true".equals(isShow) && !"false".equals(isShow)){
                return RestResponse.failure("设置参数不正确");
            }
        }
        Boolean showFalg = Boolean.valueOf(isShow);
        SysMenu menu = sysMenuService.getById(id);
        menu.setIsShow(showFalg);
        sysMenuService.saveOrUpdateMenu(menu);
        return RestResponse.success();

    }

}
